<template>
  <div
    v-loading="loading || getSaveDataLoading"
    class="add_good_container"
    element-loading-text="加载中..."
  >
    <!-- <el-header class="appcontainer">
      <el-row class="header_tabs" :style="{ width: lookW + 'px' }" justify="space-evenly">
        <el-col :span="4" v-for="(item, index) in listItem" class="item_title" :class="{ is_bg: index == itemIndex }"
          :key="index" @click="onclickIndex(index)">{{ item }}</el-col>
      </el-row>
    </el-header> -->
    <div class="header">
      <h3 class="title">{{ pageTitle }}</h3>
      <div class="btn_group">
        <HPlainButton @click="saveData(formInfo)">保存</HPlainButton>
        <HButton @click="onCancel">取消</HButton>
      </div>
    </div>

    <div class="body">
      <el-collapse
        id="sy0"
        :model-value="activeNames.includes('1') ? '1' : ''"
        @change="handleChange('1')"
      >
        <el-collapse-item name="1">
          <template #title>
            <div>
              <el-icon v-if="activeNames.includes('1')">
                <CaretBottom />
              </el-icon>
              <el-icon v-else>
                <CaretRight />
              </el-icon>
              <span>基本信息</span>
            </div>
          </template>
          <div class="basic_info_form">
            <el-form
              ref="formInfo"
              :model="infoForm"
              :rules="rulesForm"
              label-width="85"
              inline-message
            >
              <div class="main">
                <div class="item_form">
                  <!--物料编号-->
                  <div class="code">
                    <el-form-item label="物料编号" prop="code">
                      <el-input
                        v-model.trim="infoForm.code"
                        clearable
                        placeholder="如无编号系统自动生成"
                      />
                    </el-form-item>
                    <div class="icon">
                      <el-tooltip content="用于商家内部管理所使用的自定义简易编号" placement="top">
                        <el-icon color="#999" size="18">
                          <WarningFilled />
                        </el-icon>
                      </el-tooltip>
                    </div>
                  </div>

                  <!--物料类型-->
                  <el-form-item label="物料类型" prop="type">
                    <el-select
                      v-model="infoForm.type"
                      placeholder="请选择成品/物料"
                      :disabled="route.params.id != undefined"
                      @change="typeChange"
                    >
                      <el-option
                        v-for="item in options2"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                  <!--物料品牌-->
                  <el-form-item label="物料品牌" prop="brand">
                    <el-select
                      v-model="infoForm.brand"
                      placeholder="请选择物料品牌"
                      clearable
                      :loading="getBrandOptionsLoading"
                    >
                      <template #header>
                        <div class="select_header">
                          <el-input
                            v-model.trim="getBrandOptionsKeyword"
                            @keyup.enter="getBrandOptions"
                          />
                          <h-plain-button @click="getBrandOptions">搜索</h-plain-button>
                        </div>
                      </template>
                      <el-option
                        v-for="item in brandOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </div>
                <div class="item_form">
                  <!--物料名称-->
                  <el-form-item label="物料名称" prop="name">
                    <el-input v-model.trim="infoForm.name" placeholder="请输入物料名称" clearable />
                  </el-form-item>
                  <!--物料型号-->
                  <el-form-item label="物料型号" prop="model">
                    <el-input
                      v-model.trim="infoForm.model"
                      placeholder="请输入物料型号"
                      clearable
                    />
                  </el-form-item>
                  <!--物料分类-->
                  <el-form-item label="物料分类" prop="typeIds">
                    <el-cascader
                      ref="cascader"
                      v-model="infoForm.typeIds"
                      clearable
                      :props="CascaderProps"
                      :options="goodsTypeList"
                      @change="cascaderChange()"
                    >
                      <template #default="{ node, data }">
                        <span>{{ data.name }}</span>
                        <span v-if="!node.isLeaf"> ({{ data.childData.length }}) </span>
                      </template>
                    </el-cascader>
                  </el-form-item>
                </div>

                <div class="item_form">
                  <!--物料单位-->
                  <el-form-item label="物料单位" prop="unit">
                    <el-select
                      v-model="infoForm.unit"
                      placeholder="请选择物料单位"
                      clearable
                      :loading="getUnitOptionsLoading"
                    >
                      <template #header>
                        <div class="select_header">
                          <el-input
                            v-model.trim="getUnitOptionsKeyword"
                            @keyup.enter="getUnitOptions"
                          />
                          <h-plain-button @click="getUnitOptions">搜索</h-plain-button>
                        </div>
                      </template>
                      <el-option
                        v-for="item in unitOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>

                  <!--供应商-->
                  <el-form-item v-if="infoForm.type == '物料'" label="供应商" prop="supplier">
                    <el-input v-model.trim="infoForm.supplier" placeholder="物料供应商" clearable />
                  </el-form-item>

                  <!--联系电话-->
                  <el-form-item v-if="infoForm.type == '物料'" label="联系电话" prop="phone">
                    <el-input
                      v-model.trim="infoForm.phone"
                      placeholder="供应商联系电话"
                      clearable
                    />
                  </el-form-item>

                  <!--质保登记-->
                  <el-form-item v-if="infoForm.type == '成品'" label="质保登记" prop="war">
                    <el-select v-model="infoForm.war" clearable placeholder="启用/关闭">
                      <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>

                  <!--是否为核心件-->
                  <el-form-item label="是否为核心件" prop="phone">
                    <el-radio-group v-model="infoForm.coreMaterials">
                      <el-radio :value="true">是</el-radio>
                      <el-radio :value="false">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>

                <div v-if="infoForm.type == '成品'" class="item_form">
                  <el-form-item label="服务形式">
                    <el-select
                      v-model="serviceFormSelectIdList"
                      placeholder="请选择服务形式"
                      multiple
                      collapse-tags
                      collapse-tags-tooltip
                      :max-collapse-tags="1"
                      :loading="
                        getOrderModuleOptionListLoading || getReturnFactoryModuleOptionListLoading
                      "
                      filterable
                      :filter-method="handleGetServiceFormOptionList"
                      @change="handleServiceFormChange"
                    >
                      <el-option-group
                        v-for="(group, groupIndex) in serviceFormOptionList"
                        :key="groupIndex"
                        :label="group.label"
                      >
                        <el-option
                          v-for="(option, optionIndex) in group.options"
                          :key="optionIndex"
                          :value="option.value"
                          :label="option.label"
                          :disabled="option.disabled"
                        >
                          <div style="padding-left: 10px; box-sizing: border-box">{{
                            option.label
                          }}</div>
                        </el-option>
                      </el-option-group>
                    </el-select>
                  </el-form-item>
                </div>

                <!--物料货号-->
                <!-- <el-form-item label="物料货号" prop="item">
                  <el-input v-model="infoForm.item" placeholder="如无货号系统自动生成" clearable />
                </el-form-item> -->
                <!-- <div v-if="infoForm.type === '成品'" class="item_form"> -->
                <!--蓝牙二维码图片-->
                <!-- <el-form-item label="蓝牙二维码">
                    <div class="img_list">
                      <h-image
                        v-if="infoForm.qrImage"
                        :width="80"
                        :height="50"
                        :padding="2"
                        :src="infoForm.qrImage"
                        @del="handleRemoveQr"
                      ></h-image>
                      <el-upload
                        v-else
                        action="#"
                        accept="image/*"
                        :auto-upload="false"
                        :on-change="getProImagesQr"
                        :show-file-list="false"
                      >
                        <el-icon :size="24" color="#007cff">
                          <UploadFilled />
                        </el-icon>
                      </el-upload>
                    </div>
                  </el-form-item> -->
                <!-- </div> -->
                <div class="item_form">
                  <!--物料图片-->
                  <el-form-item label="物料图片">
                    <div class="img_list">
                      <h-image
                        v-for="(file, fileIndex) in infoForm.fileList"
                        :key="fileIndex"
                        :width="80"
                        :height="50"
                        :padding="2"
                        :src="file.url"
                        :preview-src-list="infoForm.fileList.map((file) => file.url)"
                        :initial-index="fileIndex"
                        fit="contain"
                        @del="handleRemove(file)"
                      />
                      <el-upload
                        v-if="infoForm.fileList.length < 10"
                        action="#"
                        multiple
                        accept=".jpg,.png,.webp,.gif"
                        :auto-upload="false"
                        :on-change="getProImages"
                        :show-file-list="false"
                      >
                        <el-icon :size="24" color="#007cff">
                          <UploadFilled />
                        </el-icon>
                      </el-upload>
                    </div>
                  </el-form-item>
                </div>
              </div>
            </el-form>
          </div>
        </el-collapse-item>
      </el-collapse>
      <el-collapse
        id="sy1"
        :model-value="activeNames.includes('2') ? '2' : ''"
        @change="handleChange('2')"
      >
        <el-collapse-item name="2">
          <template #title>
            <div style="display: flex; align-items: center; gap: 5px">
              <div>
                <el-icon v-if="activeNames.includes('2')">
                  <CaretBottom />
                </el-icon>
                <el-icon v-else>
                  <CaretRight />
                </el-icon>
                <span>物料规格</span>
              </div>
            </div>
          </template>
          <div class="specification">
            <el-table
              stripe
              resizable
              :border="true"
              :data="tableData"
              style="width: 100%"
              max-height="330"
            >
              <el-table-column label="序号" width="50" fixed="left" :align="'center'">
                <template #default="item">{{ item.$index + 1 }}</template>
              </el-table-column>
              <el-table-column label="规格名称" min-width="140">
                <template #default="item">
                  <el-input v-model.trim="item.row.name" clearable />
                </template>
              </el-table-column>
              <el-table-column label="sku码" width="300">
                <template #default="item">
                  <el-input
                    v-model.trim="item.row.code"
                    clearable
                    placeholder="如无则系统自动生成"
                  />
                </template>
              </el-table-column>
              <el-table-column width="180">
                <template #header>
                  质保周期
                  <el-popover placement="top-start" :width="160" trigger="hover">
                    <h5 style="margin-bottom: 10px">批量填充质保周期</h5>
                    <el-input
                      v-model.trim="num2"
                      placeholder="请输入"
                      clearable
                      @keyup.enter="changeNumber(2)"
                    />
                    <div style="display: flex; justify-content: end; margin-top: 10px">
                      <HButton :height="20" type="primary" :padding-lr="4" @click="changeNumber(2)"
                        >确定</HButton
                      >
                    </div>
                    <template #reference>
                      <span class="multiple_btn">批量</span>
                    </template>
                  </el-popover>
                </template>
                <template #default="item">
                  <div class="warr_day">
                    <el-input
                      v-model.trim="item.row.warrantyDay"
                      clearable
                      style="width: 60px"
                      @input="item.row.warrantyDay = item.row.warrantyDay.replace(/\D/g, '')"
                    />
                    <span class="day">天</span>
                  </div>
                </template>
              </el-table-column>

              <!-- 单价 -->
              <el-table-column width="180">
                <template #header>
                  单价
                  <el-popover placement="top-start" :width="160" trigger="hover">
                    <h5 style="margin-bottom: 10px">批量填充单价</h5>
                    <el-input
                      v-model.trim="num"
                      placeholder="请输入"
                      clearable
                      @keyup.enter="changeNumber(1)"
                    />
                    <div style="display: flex; justify-content: end; margin-top: 10px">
                      <HButton :height="20" type="primary" :padding-lr="4" @click="changeNumber(1)"
                        >确定</HButton
                      >
                    </div>
                    <template #reference>
                      <span class="multiple_btn">批量</span>
                    </template>
                  </el-popover>
                </template>
                <template #default="item">
                  <el-input
                    v-model.trim="item.row.price"
                    clearable
                    @input="item.row.price = item.row.price.replace(/\D/g, '')"
                  />
                </template>
              </el-table-column>

              <!-- <el-table-column label="单价2" width="180">
                <template #default="item">
                  <el-input
                    v-model.trim="item.row.overPrice"
                    clearable
                    @input="item.row.overPrice = item.row.overPrice.replace(/\D/g, '')"
                  />
                </template>
              </el-table-column> -->

              <el-table-column label="主图" width="120">
                <template #default="scope">
                  <el-upload
                    v-if="!tableData[scope.$index].image"
                    accept="image/*"
                    :auto-upload="false"
                    :show-file-list="false"
                    :on-change="(file: UploadFile) => handleUploadSpecificationsImg(file, scope.$index)"
                    class="primary-picture"
                  >
                    <el-icon :size="24" color="#007cff">
                      <UploadFilled />
                    </el-icon>
                  </el-upload>
                  <h-image
                    v-else
                    :width="80"
                    :height="50"
                    :src="tableData[scope.$index].image || uploadDefaultImg"
                    :padding="2"
                    fit="contain"
                    @del="handleDelSpecificationsImg(scope.$index)"
                  >
                  </h-image>
                </template>
              </el-table-column>
              <el-table-column label="操作" prop="operate" width="100" fixed="right">
                <template #default="scope">
                  <el-space :size="0" :spacer="spacer">
                    <h-link
                      v-if="tableData.length > 1"
                      type="error"
                      @click="deleteLineData(scope.$index, scope.row)"
                      >删除</h-link
                    >
                    <h-link v-if="scope.$index === 0" @click="addLineData">添加</h-link>
                  </el-space>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-collapse-item>
      </el-collapse>
      <el-collapse
        id="sy2"
        :model-value="activeNames.includes('3') ? '3' : ''"
        @change="handleChange('3')"
      >
        <el-collapse-item name="3">
          <template #title>
            <div>
              <el-icon v-if="activeNames.includes('3')"> <CaretBottom /> </el-icon
              ><el-icon v-else>
                <CaretRight />
              </el-icon>
              <span>物料参数</span>
            </div>
          </template>
          <div class="good_parameter">
            <div v-loading="getCustomFieldLoading" class="form">
              <el-form
                ref="formSpec"
                label-position="right"
                :model="paraForm"
                :rules="rulesForm"
                label-width="60"
                inline-message
              >
                <el-form-item label="选择参数" prop="para">
                  <el-select
                    v-model="paraForm.para"
                    clearable
                    placeholder="请选择参数"
                    @change="getFields"
                  >
                    <el-option
                      v-for="item in paraForm.paraOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>

                <!-- 自定义字段 -->
                <el-form-item
                  v-for="(field, fieldIndex) in customFieldRender.txtSelect"
                  :key="fieldIndex"
                  :label="field.name"
                  :prop="field.formItemProp"
                  :rules="field.rules"
                >
                  <template #label>
                    <h-tooltip-text :max-width="48" :height="16" :text="field.name">
                      {{ field.name }}
                    </h-tooltip-text>
                  </template>
                  <el-input
                    v-if="field.type === 1 && paraForm.fieldInfo[field.sourceArrIndex]"
                    v-model.trim="paraForm.fieldInfo[field.sourceArrIndex].val"
                    :placeholder="field.tip"
                    clearable
                    type="text"
                  />
                  <el-select
                    v-if="field.type === 3 && paraForm.fieldInfo[field.sourceArrIndex]"
                    v-model="paraForm.fieldInfo[field.sourceArrIndex].val"
                    :placeholder="field.tip"
                    clearable
                  >
                    <el-option
                      v-for="(option, index) in field.strs"
                      :key="index"
                      :label="option"
                      :value="option"
                    />
                  </el-select>
                  <el-select
                    v-if="field.type === 4 && paraForm.fieldInfo[field.sourceArrIndex]"
                    v-model="paraForm.fieldInfo[field.sourceArrIndex].val"
                    :placeholder="field.tip"
                    clearable
                    collapse-tags
                    collapse-tags-tooltip
                    multiple
                  >
                    <el-option
                      v-for="(option, index) in field.strs"
                      :key="index"
                      :label="option"
                      :value="option"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item
                  v-for="(field, fieldIndex) in customFieldRender.radioCheckboxRate"
                  :key="fieldIndex"
                  :label="field.name"
                  :prop="field.formItemProp"
                  :rules="field.rules"
                >
                  <template #label>
                    <h-tooltip-text :max-width="48" :height="16" :text="field.name">
                      {{ field.name }}
                    </h-tooltip-text>
                  </template>
                  <el-radio-group
                    v-if="field.type === 3 && paraForm.fieldInfo[field.sourceArrIndex]"
                    v-model="paraForm.fieldInfo[field.sourceArrIndex].val"
                  >
                    <el-radio
                      v-for="(option, optionIndex) in field.strs"
                      :key="optionIndex"
                      :value="option"
                      size="small"
                      >{{ option }}</el-radio
                    >
                  </el-radio-group>
                  <el-checkbox-group
                    v-if="field.type === 4 && paraForm.fieldInfo[field.sourceArrIndex]"
                    v-model="paraForm.fieldInfo[field.sourceArrIndex].val"
                  >
                    <el-checkbox
                      v-for="(option, index) in field.strs"
                      :key="index"
                      :value="option"
                      size="small"
                    >
                      {{ option }}
                    </el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
                <el-form-item
                  v-for="(field, fieldIndex) in customFieldRender.uploadFile"
                  :key="fieldIndex"
                  :label="field.name"
                  :prop="field.formItemProp"
                  :rules="field.rules"
                >
                  <template #label>
                    <h-tooltip-text :max-width="48" :height="16" :text="field.name">
                      {{ field.name }}
                    </h-tooltip-text>
                  </template>
                  <el-upload
                    v-if="paraForm.fieldInfo[field.sourceArrIndex]"
                    v-model="paraForm.fieldInfo[field.sourceArrIndex].imgarr"
                    :auto-upload="false"
                    :accept="field.type == 5 ? 'image/*' : field.type == 6 ? '.pdf' : 'video/*'"
                    drag
                    action="#"
                    multiple
                    :show-file-list="false"
                    :on-change="
                      (file) => {
                        handleChange1(file, paraForm.fieldInfo[field.sourceArrIndex])
                      }
                    "
                  >
                    <el-icon size="28" color="#606266"><upload-filled /></el-icon>
                    <div style="color: #606266; font-size: 12px; line-height: 16px; height: 16px">{{
                      field.type == 5
                        ? '点击上传图片'
                        : field.type == 6
                        ? '点击上传附件'
                        : '点击上传视频'
                    }}</div>
                  </el-upload>
                  <ul
                    v-if="
                      paraForm.fieldInfo[field.sourceArrIndex] &&
                      paraForm.fieldInfo[field.sourceArrIndex].imgarr.length >= 1
                    "
                    class="files"
                  >
                    <li
                      v-for="(file, index) in paraForm.fieldInfo[field.sourceArrIndex].imgarr"
                      :key="index"
                      class="file"
                    >
                      <h-image
                        v-if="
                          (file.name
                            ? file.name
                            : file.image.split('/')[file.image.split('/').length - 1]
                          ).replace(/.+\./, '') == 'pdf'
                        "
                        :src="pdf"
                        :width="80"
                        :height="50"
                        :is-show-img-preview="false"
                        @preview="lookFile(file.image, '附件')"
                        @del="deleteItem1(paraForm.fieldInfo[field.sourceArrIndex], index)"
                      />
                      <h-image
                        v-else-if="
                          file.file
                            ? file.file.type.includes('video/')
                            : /\.(swf|avi|flv|mpg|rm|mov|wav|asf|3gp|mkv|rmvb|mp4)$/.test(
                                file.image.toLowerCase(),
                              )
                        "
                        :width="80"
                        :height="50"
                        :src="videoPlaceholderImg"
                        :is-show-img-preview="false"
                        @preview="lookFile(file.image, '视频')"
                        @del="deleteItem1(paraForm.fieldInfo[field.sourceArrIndex], index)"
                      />
                      <h-image
                        v-else
                        :width="80"
                        :height="50"
                        :src="file.image"
                        :preview-src-list="
                          paraForm.fieldInfo[field.sourceArrIndex].imgarr.map((item) => item.image)
                        "
                        @del="deleteItem1(paraForm.fieldInfo[field.sourceArrIndex], index)"
                      />
                      <h-tooltip-text
                        :max-width="80"
                        :height="16"
                        :text="
                          file.name
                            ? file.name
                            : file.image.split('/')[file.image.split('/').length - 1]
                        "
                      >
                        {{
                          file.name
                            ? file.name
                            : file.image.split('/')[file.image.split('/').length - 1]
                        }}
                      </h-tooltip-text>
                    </li>
                  </ul>
                </el-form-item>
                <el-form-item
                  v-for="(field, fieldIndex) in customFieldRender.textarea"
                  :key="fieldIndex"
                  :label="field.name"
                  :prop="field.formItemProp"
                  :rules="field.rules"
                >
                  <template #label>
                    <h-tooltip-text :max-width="48" :height="16" :text="field.name">
                      {{ field.name }}
                    </h-tooltip-text>
                  </template>
                  <el-input
                    v-if="paraForm.fieldInfo[field.sourceArrIndex]"
                    v-model.trim="paraForm.fieldInfo[field.sourceArrIndex].val"
                    :placeholder="field.tip"
                    clearable
                    type="textarea"
                    resize="both"
                    maxlength="200"
                    show-word-limit
                  />
                </el-form-item>
              </el-form>
            </div>
            <div class="table">
              <el-table
                stripe
                resizable
                :border="true"
                :data="selfData"
                style="width: 100%"
                max-height="270"
              >
                <el-table-column label="序号" width="50" fixed="left" :align="'center'">
                  <template #default="item">
                    <span> {{ item.$index + 1 }} </span>
                  </template>
                </el-table-column>
                <el-table-column prop="name" label="自定义参数名称">
                  <template #default="scope">
                    <el-input
                      v-model.trim="scope.row.name"
                      clearable
                      placeholder="请输入参数名称"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="address" label="参数值">
                  <template #default="scope">
                    <el-input v-model.trim="scope.row.val" clearable placeholder="请输入参数值" />
                  </template>
                </el-table-column>
                <el-table-column prop="operate" label="操作" width="100">
                  <template #default="scope">
                    <el-space :size="0" :spacer="spacer">
                      <h-link type="error" @click="deleteParameter(scope.$index, scope.row.id)"
                        >删除</h-link
                      >
                      <h-link v-if="scope.$index === 0" @click="addParameter">添加</h-link>
                    </el-space>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
      <el-collapse
        id="sy4"
        :model-value="activeNames.includes('5') ? '5' : ''"
        @change="handleChange('5')"
      >
        <el-collapse-item name="5">
          <template #title>
            <div>
              <el-icon v-if="activeNames.includes('5')">
                <CaretBottom />
              </el-icon>
              <el-icon v-else>
                <CaretRight />
              </el-icon>
              <span>物料详情</span>
            </div>
          </template>
          <div class="editor_container">
            <Editor
              ref="editorRef"
              style="height: 100%"
              :value="ediorData.content"
              :main-style="{ height: '100%' }"
            />
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>

    <!--物料规格-->

    <!--先隐藏，后续可能会用到-->
    <!--<el-collapse-->
    <!--  v-if="infoForm.type == '成品'"-->
    <!--  id="sy3"-->
    <!--  :model-value="activeNames.includes('4') ? '4' : ''"-->
    <!--  class="bor_padding"-->
    <!--  @change="handleChange('4')"-->
    <!--&gt;-->
    <!--  <el-collapse-item name="4">-->
    <!--    <template #title>-->
    <!--      <div>-->
    <!--        <el-icon v-if="activeNames.includes('4')">-->
    <!--          <CaretBottom />-->
    <!--        </el-icon>-->
    <!--        <el-icon v-else>-->
    <!--          <CaretRight />-->
    <!--        </el-icon>-->
    <!--        <span>物料资料</span>-->
    <!--      </div>-->
    <!--    </template>-->
    <!--    <div class="main_content">-->
    <!--      <div style="display: flex; gap: 5px">-->
    <!--        <HPlainButton @click="productDrawerShow">-->
    <!--          <el-icon size="14" class="icon_btn">-->
    <!--            <Document />-->
    <!--          </el-icon>-->
    <!--          物料说明书-->
    <!--          <el-icon class="icon_arr_right">-->
    <!--            <ArrowRight />-->
    <!--          </el-icon>-->
    <!--        </HPlainButton>-->
    <!--        <HPlainButton @click="vidoeDrawerShow">-->
    <!--          <el-icon size="14" class="icon_btn">-->
    <!--            <VideoCameraFilled />-->
    <!--          </el-icon>-->
    <!--          物料视频-->
    <!--          <el-icon class="icon_arr_right">-->
    <!--            <ArrowRight />-->
    <!--          </el-icon>-->
    <!--        </HPlainButton>-->
    <!--        <HPlainButton>-->
    <!--          <el-icon size="14" class="icon_btn">-->
    <!--            <Link />-->
    <!--          </el-icon>-->
    <!--          增加自定义链接-->
    <!--          <el-icon class="icon_arr_right">-->
    <!--            <ArrowRight />-->
    <!--          </el-icon>-->
    <!--        </HPlainButton>-->
    <!--      </div>-->
    <!--    </div>-->
    <!--  </el-collapse-item>-->
    <!--</el-collapse>-->

    <!-- 文件查看 -->
    <el-dialog
      v-model="dialogContract"
      :title="`查看${file.type}`"
      :draggable="true"
      :destroy-on-close="true"
      :close-on-click-modal="false"
    >
      <iframe
        :src="`${file.file}`"
        width="100%"
        height="100%"
        style="height: 700px"
        frameborder="0"
      ></iframe>
    </el-dialog>

    <!--修改物料规格弹窗  -->
    <el-dialog v-model="dialogspec" title="物料规格" width="40%" draggable>
      <el-checkbox-group v-model="checkList" class="spec_show">
        <el-checkbox v-for="(item, index) in selectspecdata" :key="index" :value="item.value"
          ><span class="label_color">{{ item.title }}</span></el-checkbox
        >
      </el-checkbox-group>
      <template #footer>
        <div style="display: flex; justify-content: flex-end; gap: 10px">
          <HButton is-modal type="primary" @click="Confirm">确定</HButton>
          <HButton is-modal @click="dialogspec = false"> 取消 </HButton>
        </div>
      </template>
    </el-dialog>

    <!-- 说明书弹窗 -->
    <el-drawer v-model="productDrawer" title="关联说明书" show-close size="700px">
      <div class="pro_information">
        <p>根据当前产品所需要的相关说明书数据进行关联，后期展示和数据查询快速匹配</p>
        <el-transfer
          v-model="filtervalue"
          :titles="['说明书库', '已关联说明书']"
          filterable
          :filter-method="filterMethod"
          filter-placeholder="请输入搜索内容"
          :data="insData"
        >
          <template #default="{ option }">
            <div class="list_item">
              <span>{{ option.label }}</span
              ><el-icon>
                <Picture></Picture>
              </el-icon>
            </div>
          </template>
        </el-transfer>
        <footer class="btn_drawer" style="display: flex; justify-content: flex-end; gap: 10px">
          <HButton is-modal type="primary" @click="saveInsbooks">保存</HButton>
          <HButton is-modal @click="productDrawer = false">取消</HButton>
        </footer>
      </div>
    </el-drawer>

    <!-- 视频弹窗 -->
    <el-drawer v-model="videoDialog" title="关联视频" show-close size="700px">
      <div class="pro_information">
        <p>根据当前产品所需要的相关视频数据进行关联，后期展示和数据查询快速匹配</p>
        <el-transfer
          v-model="videoValue"
          :titles="['视频库', '已关联视频']"
          filterable
          :filter-method="filterVideo"
          filter-placeholder="请输入搜索内容"
          :data="videoData"
        >
          <template #default="{ option }">
            <div class="list_item">
              <span>{{ option.label }}</span
              ><el-icon>
                <Picture></Picture>
              </el-icon>
            </div>
          </template>
        </el-transfer>
        <footer class="btn_drawer" style="display: flex; justify-content: flex-end; gap: 10px">
          <HButton is-modal type="primary" @click="saveVideo">保存</HButton>
          <HButton is-modal @click="videoDialog = false">取消</HButton>
        </footer>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, reactive, watch, h, nextTick, computed } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import type { FormInstance, FormRules, UploadFile } from 'element-plus'
  import { ElDivider, ElMessage } from 'element-plus'
  import { useSettingStore } from '@/store/modules/setting'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import pdf from './../../../assets/image/pdf.png'
  import _ from 'lodash'
  import {
    typePageSelect,
    brandPageSelect,
    unitPageSelect,
    paramPageSelect,
    getParamFields,
    productSave,
    getInfo,
    getInsDetail,
    spareSave,
    getSpareInfo,
    getGoodsType,
  } from '@/api/goodsInfo'
  import { proAnnexUpload, deleteFile } from '@/api/upload'
  import { instrList, getVideoList } from '@/api/knowledge'
  import { orderAnnexUpload, orderVideoUpload } from '@/api/upload'
  import { CaretBottom, CaretRight, UploadFilled } from '@element-plus/icons-vue'
  import uploadDefaultImg from '@/assets/image/avatar_upload_default.png'
  import { CustomFieldRender } from './types'
  import videoPlaceholderImg from '@/assets/image/pages/order/new/video.png'
  import { useGoodType } from '../services'
  import Editor from '@/components/business/editor/Editor.vue'
  import routeComponentName from '@/config/route-component-name'
  import { HMessageBox } from '@/components/common/message'
  import { useGetModuleOptions as useGetOrderModuleOptionList } from '@/services/pages/order/useModule'
  import { useGetOptions as useGetReturnFactoryModuleOptionList } from '@/services/pages/return-factory/useModule'

  const {
    options: orderModuleOptionList,
    getOptionsLoading: getOrderModuleOptionListLoading,
    getOptionsKeyword: getOrderModuleOptionListKeyword,
    getOptions: getOrderModuleOptionList,
  } = useGetOrderModuleOptionList()

  const {
    options: returnFactoryModuleOptionList,
    getOptionsLoading: getReturnFactoryModuleOptionListLoading,
    getOptionsParam: getReturnFactoryModuleOptionParam,
    getOptions: getReturnFactoryModuleOptionList,
  } = useGetReturnFactoryModuleOptionList()

  defineOptions({
    name: routeComponentName.good.goodForm,
  })

  // 服务形式下拉选项
  const serviceFormOptionList = computed(() => {
    return [
      {
        label: '工单模块',
        options: orderModuleOptionList.value.map((item) => {
          return {
            label: item.name,
            value: item.id,
            type: 1,
            disabled: item.disabled,
          }
        }),
      },
      {
        label: '返厂模块',
        options: returnFactoryModuleOptionList.value.map((item) => {
          return {
            label: item.name,
            value: item.id,
            type: 2,
            disabled: item.disabled,
          }
        }),
      },
    ]
  })

  // 服务形式选中的模块
  const serviceFormSelectIdList = ref<Array<string>>([])

  // 编辑器组件实例
  const editorRef = ref<InstanceType<typeof Editor> | null>(null)

  const { getGoodType } = useGoodType()

  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })
  const cascader = ref()
  // 分类变化
  const cascaderChange = () => {
    if (infoForm.typeIds && infoForm.typeIds.length > 0) {
      cascader.value.togglePopperVisible()
    }
  }

  const isFillGoodType = ref(false)
  const pageTitle = ref('')
  const TagsViewStore = useTagsViewStore()
  const router = useRouter()
  const route = useRoute()
  const listItem = ref(['基本信息', '物料规格', '物料参数', '物料资料', '物料详情'])
  const num = ref()
  const num2 = ref()
  // 批量填充数量
  const changeNumber = (val) => {
    switch (val) {
      case 1:
        if (num.value) {
          tableData.value.forEach((item) => {
            item.price = num.value
          })
        }
        break
      case 2:
        if (num2.value) {
          tableData.value.forEach((item) => {
            item.warrantyDay = num2.value
          })
        }
        break
      default:
        break
    }
  }
  const productDrawer = ref(false)
  const videoDialog = ref(false)

  const dialogspec = ref(false)
  // ********************级联选择分类*********************
  const CascaderProps = ref({
    value: 'id',
    label: 'name',
    children: 'childData',
    checkStrictly: true,
  })
  // 获取列表
  const goodsTypeList = ref([])
  const getGoodsTypeFun = async () => {
    await getGoodsType().then((res) => {
      if (res.data.code == 20000) {
        goodsTypeList.value = res.data.data.rows
      }
    })
  }
  // 自定义参数
  const selfData = ref([
    {
      name: '',
      val: '',
    },
  ])
  // 添加自定义参数
  const addParameter = () => {
    let temp = {
      name: '',
      val: '',
    }
    selfData.value.push(temp)
  }
  // 删除自定义参数
  const deleteParameter = (index, id) => {
    selfData.value = selfData.value.filter((o, i) => i != index)
    if (id) {
      paraForm.itemIDs.push(id)
    }
    if (selfData.value.length == 0) {
      addParameter()
    }
  }
  // 穿梭框 -----start------

  const insData = ref([])
  const filtervalue = ref([]) // 选中的说明书

  const videoData = ref([])
  const videoValue = ref([]) // 选中的视

  /**
   * 获取服务形式下拉选项
   * @param keyword - 搜索关键字
   */
  const handleGetServiceFormOptionList = _.debounce((keyword: string) => {
    if (getOrderModuleOptionListKeyword.value !== keyword) {
      getOrderModuleOptionListKeyword.value = keyword
      getOrderModuleOptionList()
    }

    if (getReturnFactoryModuleOptionParam.value.name !== keyword) {
      getReturnFactoryModuleOptionParam.value.name = keyword
      getReturnFactoryModuleOptionList()
    }
  }, 600)

  /**
   * 服务形式选择事件
   */
  const handleServiceFormChange = (moduleIdList: Array<string>) => {
    infoForm.productModuleRelationVos = moduleIdList.map((moduleId) => {
      const orderModule = orderModuleOptionList.value.find((module) => module.id === moduleId)
      const returnModule = returnFactoryModuleOptionList.value.find(
        (module) => module.id === moduleId,
      )
      if (orderModule || returnModule) {
        return {
          moduleId,
          type: orderModule ? 1 : 2,
        }
      }
    })
  }

  // 刷新页面
  const refresh = () => {
    useSettingStore().setReload()
  }

  // 说明书弹窗
  const productDrawerShow = () => {
    insData.value = []
    productDrawer.value = true
    const tmp = {
      limit: 0,
      name: '',
      page: 0,
    }
    instrList(tmp).then((res) => {
      res.data.data.rows.forEach((item) => {
        insData.value.push({
          key: item.id,
          label: item.name,
        })
      })
    })
  }

  // 视频弹窗
  const vidoeDrawerShow = () => {
    videoData.value = []
    videoDialog.value = true
    const tmp = {
      limit: 0,
      name: '',
      page: 0,
    }
    getVideoList(tmp).then((res) => {
      res.data.data.rows.forEach((item) => {
        if (videoData.value.indexOf(item) == -1) {
          videoData.value.push({
            key: item.id,
            label: item.name,
          })
        }
      })
    })
  }

  const filterMethod = (query, item) => {
    return item.label.toLowerCase().includes(query.toLowerCase())
  }

  const filterVideo = (query, item) => {
    return item.label.toLowerCase().includes(query.toLowerCase())
  }

  // 保存说明书
  const saveInsbooks = () => {
    productDrawer.value = false
  }

  // 保存视频
  const saveVideo = () => {
    videoDialog.value = false
  }

  // 穿梭框----end----

  // 物料规格 ----start------

  // 选择的规格内容
  const listData = ref([])
  const connentArr = ref([]) // 保存重复的数量
  const indexArr = ref([]) // 保存重复的间隔index
  const form = ref({})
  const specData = ref([])
  const nameIndex = ref(1)
  const tableData = ref([
    {
      code: '', //sku
      enabled: true, //启用
      image: '', //主图
      name: `默认规格${nameIndex.value}`,
      price: '0', //价格
      overPrice: '0', //过保价格
      warrantyDay: '30', //质保
    },
  ])
  const delSepcIds = ref([]) // 删除的物料规格ID集合
  // 规格类型数据
  const selectspecdata = ref([
    {
      value: 'a',
      title: '品牌',
      checkList: ['美的', '格力', '海尔'],
    },
    {
      value: 'b',
      title: '颜色',
      checkList: ['白色', '黑色', '灰色', '红色'],
    },
    {
      value: 'c',
      title: '尺寸',
      checkList: ['10cm', '20cm', '30cm'],
    },
    {
      value: 'd',
      title: '内存',
      checkList: ['1G', '2G', '5G', '10G'],
    },
  ])
  interface SpanMethodProps {
    rowIndex: number
    columnIndex: number
  }

  const objectSpanMethod = ({ rowIndex, columnIndex }: SpanMethodProps) => {
    const vals = Object.values(form.value)
    if (columnIndex > 0) {
      if (columnIndex <= vals.length) {
        const index = indexArr.value[columnIndex - 1].indexOf(rowIndex)
        if (index !== -1) {
          return {
            rowspan: connentArr.value[columnIndex - 1][index],
            colspan: 1,
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0,
          }
        }
      }
    }
  }

  // 物料规格内容变化
  const changeModel = (val) => {
    form.value = {}
    listData.value.forEach((o) => {
      if (o.checkList.length > 0) {
        form.value[o.value] = o.checkList
      }
    })
    tableData.value = []
    var arrGroup = Object.values(form.value)
    var arrStack = []
    var strStack = []
    combination(arrStack, strStack, arrGroup, arrGroup.length, 0)
    connentArr.value = []
    indexArr.value = []
    const obj = _.cloneDeep(form.value) // 记录数量
    for (const i in obj) {
      obj[i] = []
    }
    const obj2 = _.cloneDeep(obj) // 记录位置

    for (const j in obj) {
      let save = ''
      let num = -1
      for (const i in tableData.value) {
        if (save === tableData.value[i][j]) {
          obj[j][num]++
        } else {
          num++
          obj[j].push(1)
          obj2[j].push(Number(i))
        }
        save = tableData.value[i][j]
      }
    }
    for (const i in form.value) {
      connentArr.value.push(obj[i])
      indexArr.value.push(obj2[i])
    }
  }
  /**
   * arrStack
   * strStack
   * arrGroup 数组
   * size 数组长度
   * index 下标
   * **/
  const combination = (arrStack, strStack, arrGroup, size, index) => {
    var nextIndex = index + 1
    if (nextIndex > size) {
      return
    }
    arrStack.push(arrGroup[index])
    if (arrStack.length === size) {
      combinationResult(strStack, arrStack, 0)
    }
    combination(arrStack, strStack, arrGroup, size, nextIndex)
    if (arrStack.length > 0) {
      arrStack.pop()
    }
    combination(arrStack, strStack, arrGroup, size, nextIndex)
  }
  //  合并选择的数组信息
  const combinationResult = (strStack, arrGroup, index) => {
    if (index + 1 > arrGroup.length) {
      return
    }
    var arr = arrGroup[index]
    var nextIndex = index + 1
    for (var i = 0; i < arr.length; i++) {
      strStack.push(arr[i])
      combinationResult(strStack, arrGroup, nextIndex)
      if (nextIndex + 1 > arrGroup.length) {
        const obj = {}
        let count = 0
        for (const j in form.value) {
          obj[j] = strStack[count]
          count++
        }
        let name = []
        for (const o in obj) {
          name.push(obj[o])
        }

        let tem = {
          name: name.join('、'),
          image: '',
          enabled: true,
          price: '0',
          overPrice: '0',
          warrantyDay: '30',
          code: '',
        }
        tableData.value.push({ ...tem, ...obj })
        if (tableData.value.length == 0) {
          tableData.value = [
            {
              name: '默认规格',
              image: '',
              enabled: true,
              price: '0',
              overPrice: '0',
              warrantyDay: '30',
              code: '',
            },
          ]
        }
      }
      if (strStack.length > 0) {
        strStack.pop()
      }
    }
  }

  // 修改物料规格弹窗  确定
  const Confirm = () => {
    images.value = []
    tableData.value = [
      {
        name: '默认规格',
        image: '',
        enabled: true,
        price: '0',
        overPrice: '0',
        warrantyDay: '30',
        code: '',
      },
    ]
    specData.value = selectspecdata.value.filter((o) => {
      if (checkList.value.includes(o.value)) {
        return o
      }
    })
    listData.value = specData.value.map((o) => {
      return { ...o, checkList: [] }
    })
    dialogspec.value = false
  }

  // 添加物料规格
  const addLineData = () => {
    nameIndex.value += 1
    let tt = tableData.value.some((i) => {
      return i.name == `默认规格${nameIndex.value}`
    })
    if (tt) {
      addLineData()
      return
    }
    tableData.value.push({
      code: '',
      enabled: true,
      image: '',
      name: `默认规格${nameIndex.value}`,
      price: '0',
      overPrice: '0',
      warrantyDay: '30',
    })
  }

  // 删除物料规格
  const deleteLineData = (index, obj) => {
    tableData.value.splice(index, 1)
    if (tableData.value.length == 0) {
      nameIndex.value = 0
    }
    images.value.splice(index, 1)
    if (obj.id) {
      delSepcIds.value.push(obj.id)
    }
    if (obj.image != '') {
      deleteFile([obj.image]).then()
    }
  }

  // 物料规格 ----- end-----

  const checkList = ref([])

  const options = [
    {
      value: true,
      label: '启用',
    },
    {
      value: false,
      label: '关闭',
    },
  ]

  const options2 = [
    {
      value: '成品',
      label: '成品',
    },
    {
      value: '物料',
      label: '物料',
    },
  ]

  const activeNames = ref(['1', '2', '4', '5'])

  const handleChange = (val: string) => {
    if (activeNames.value.includes(val)) {
      activeNames.value = activeNames.value.filter((o) => o != val)
    } else {
      activeNames.value.push(val)
    }
  }
  const itemIndex = ref(0)

  const onclickIndex = (index) => {
    itemIndex.value = index
    document.body.removeEventListener('scroll', listener.value)
    if (index == 3 && listItem.value.length == 4) {
      index += 1
    }
    const section = document.getElementById('sy' + index)
    const scrollTop = window.scrollY || document.documentElement.scrollTop
    const elementTop = section.offsetTop
    document.body.scrollTo({
      top: scrollTop + elementTop - 60,
      behavior: 'smooth',
    })
    setTimeout(() => {
      document.body.addEventListener('scroll', listener.value)
    }, 500)
  }
  const listener = ref(null)

  // 获取物料图片
  const getProImages = (uploadFile: UploadFile) => {
    if (infoForm.fileList.map((file) => file.uid).indexOf(uploadFile.uid) === -1) {
      const fileReader = new FileReader()
      fileReader.readAsDataURL(uploadFile.raw)
      fileReader.onload = () => {
        if (infoForm.fileList.length >= 10) {
          HMessageBox.error('最多只能上传10张图片')
          return
        }
        if (!uploadFile.raw.type.includes('image')) {
          HMessageBox.error('只能上传图片类型的文件')
          return
        }
        if (uploadFile.size / 1024 / 1024 > 10) {
          HMessageBox.error('图片必须的大小必须在10M以内')
          return
        }
        infoForm.fileList.push(Object.assign(uploadFile, { url: fileReader.result }))
      }
    }
  }

  // 删除图片
  const handleRemove = (file: UploadFile) => {
    infoForm.fileList.forEach((item, index) => {
      if (item.url == file.url) {
        infoForm.fileList.splice(index, 1)
        infoForm.imageIDs.push(item.id)
      }
    })
  }
  // 获取二维码图片
  const getProImagesQr = (uploadFile: UploadFile) => {
    infoForm.qrImages = [uploadFile]
    infoForm.qrImage = window.URL.createObjectURL(uploadFile.raw)
  }

  // 删除图片
  const handleRemoveQr = () => {
    infoForm.qrImages = []
    infoForm.qrImage = ''
  }

  const images = ref([]) // 上传到物料规格图片
  const imgRoutes = ref([]) // 删除的物料规格图片路径

  // 上传物料规格图片
  const handleUploadSpecificationsImg = (uploadFile: UploadFile, index: number) => {
    tableData.value[index].image = window.URL.createObjectURL(uploadFile.raw)
    images.value[index] = uploadFile
  }

  const handleDelSpecificationsImg = (index: number) => {
    tableData.value[index].image = ''
    images.value.splice(index, 1)
  }

  const loading = ref(false)

  const formInfo = ref<FormInstance | null>(null) // 基本信息表单Dom

  const formSpec = ref<FormInstance | null>(null) // 物料规格表单Dom

  // （上传）获取图片
  const handleChange1 = (uploadFile: UploadFile, item: any) => {
    if (item.uploadSize < uploadFile.size / 1024 / 1024) {
      HMessageBox.error(
        item.type == 5
          ? '图片'
          : item.type == 6
          ? '附件'
          : '视频' + '大小不能超过' + item.uploadSize + 'MB!',
      )
      return
    }
    if (item.imgarr.length >= item.uploadQty) {
      HMessageBox.error(
        `${item.type == 5 ? '图片' : item.type == 6 ? '附件' : '视频'} 数量不能超过 ${
          item.uploadQty
        }!`,
      )
      return
    }
    let { uid, name } = uploadFile.raw!
    let tmp = {
      uid,
      name,
      image: window.URL.createObjectURL(uploadFile.raw!),
      file: uploadFile.raw!,
    }
    item.imgarr.push(tmp)
  }
  // 删除图片
  const deleteItem1 = (itindex, index: any) => {
    paraForm.fieldInfo = paraForm.fieldInfo.map((arr) => {
      if (arr.type == 5 || arr.type == 6 || arr.type == 7) {
        if (arr.goodsParamFieldId == itindex.goodsParamFieldId) {
          arr.imgarr = arr.imgarr.filter((o, i) => i != index)
        }
      }
      return arr
    })
  }
  // 查看图片
  const file = ref({ file: null, type: '' }) //文件
  const dialogContract = ref(false) //文件查看弹窗
  const lookFile = (val, type) => {
    file.value = { file: val, type: type }
    dialogContract.value = true
  }

  // 基本信息表单数据
  const infoForm = reactive({
    proID: '',
    status: false, // 物料状态
    type: getGoodType() === 'product' ? '成品' : '物料', // 物料类型
    model: '', // 物料型号
    class: '', // 物料分类id
    className: '', // 物料分类名称
    brand: '', // 物料品牌id
    brandName: '', // 物料品牌名称
    unit: '', // 物料单位id
    unitName: '', // 物料单位名称
    name: '', // 物料名称
    item: '', // 物料货号
    war: true, // 质保登记
    code: '', // 物料编号
    fileList: [], // 物料图片
    supplier: '', // 供应商
    phone: '', // 供应商电话
    images: [], // 物料图片
    imageIDs: [], // 删除的物料图片ID集合
    typeIds: [], //物料分类层级ID
    typeNames: [], //物料分类层级名称
    qrImages: [], //二维码图片
    qrImage: '',
    productModuleRelationVos: [],
    coreMaterials: false,
  })
  const brandOptions = ref([]) // 品牌下拉
  const unitOptions = ref([]) // 单位下拉

  const typeLoading = ref(false)

  const typeVal = ref()

  const wangEdior = ref()
  const ediorData = ref({ content: '', type: 'goods' })

  // 检验规则
  const rulesForm = reactive<FormRules>({
    type: [{ required: true, message: '请选择物料类型', trigger: 'blur' }],
    model: [{ required: true, message: '请输入物料型号', trigger: 'blur' }],
    class: [{ required: true, message: '请选择物料分类', trigger: 'change' }],
    typeIds: [{ required: true, message: '请选择物料分类', trigger: 'change' }],
    brand: [{ required: true, message: '请选择物料品牌', trigger: 'change' }],
    unit: [{ required: true, message: '请选择物料单位', trigger: 'change' }],
    name: [{ required: false, message: '请输入物料名称', trigger: 'blur' }],
    item: [{ required: false, message: '请输入物料货号', trigger: 'blur' }],
    war: [{ required: true, message: '请选择质保登记', trigger: 'change' }],
    code: [{ required: false, message: '请输入物料编号', trigger: 'blur' }],
    para: [{ required: false, message: '请选择物料参数', trigger: 'blur' }],
    supplier: [{ required: false, message: '请输入供应商名称', trigger: 'blur' }],
    phone: [
      { required: false, message: '请输入供应商联系电话', trigger: 'blur' },
      {
        pattern: /^1[3|4|5|7|8|9][0-9]\d{8}$/,
        message: '请输入正确的电话',
        trigger: 'blur',
      },
    ],
  })

  // 物料参数表单数据
  const paraForm = reactive({
    paraOptions: [], // 参数下拉数据
    para: '', // 选择参数Id
    paraId: null, //获取物料参数值ID，新增不必传，修改必传
    fieldInfo: [], // 自定义字段内容list
    fieldValVos: [], //获取物料list ，新增不必传，修改必传
    paramValVo: {
      fieldValVos: null,
      id: null, //物料参数值ID，新增不必传，修改必传
      paramId: null, //物料参数ID
    }, // 物料参数对象
    itemIDs: [], // 删除的物料自定义参数ID
  })

  // 物料类型变化时
  const typeChange = (val) => {
    if (val == '成品') {
      listItem.value = ['基本信息', '物料规格', '物料参数', '物料资料', '物料详情']
      rulesForm.brand[0].required = true
    } else {
      rulesForm.brand[0].required = false
      listItem.value = ['基本信息', '物料规格', '物料参数', '物料详情']
    }
  }

  // 获取分类下拉选项
  const typeOptions = ref([])
  const getTypeOptionsLoading = ref(false)
  const getTypeOptionsKeyword = ref('')
  const getTypeOptions = async () => {
    getTypeOptionsLoading.value = true
    const res = await typePageSelect({
      limit: 0,
      name: getTypeOptionsKeyword.value,
      page: 0,
    })
    typeOptions.value = res.data.data.rows
    getTypeOptionsLoading.value = false
  }

  /**
   * 在物料列表添加完分类后，跳转到该页面就默认选中最新添加的分类
   */
  const selectGoodType = () => {
    if (route.query && route.query.goodTypeName) {
      isFillGoodType.value = true
      goodsTypeList.value.forEach((o) => {
        if (o.name == route.query.goodTypeName) {
          infoForm.typeIds = [o.id]
        } else {
          o.childData.forEach((o2) => {
            if (route.query.parentId == o.id && o2.name == route.query.goodTypeName) {
              infoForm.typeIds = [o.id, o2.id]
            } else {
              o2.childData.forEach((o3) => {
                if (route.query.parentId == o2.id && o3.name == route.query.goodTypeName) {
                  infoForm.typeIds = [o.id, o2.id, o3.id]
                }
              })
            }
          })
        }
      })
      isFillGoodType.value = false
    }
  }

  // 获取品牌下拉选项
  const getBrandOptionsKeyword = ref('')
  const getBrandOptionsLoading = ref(false)
  const getBrandOptions = async () => {
    getBrandOptionsLoading.value = true
    const res = await brandPageSelect({
      limit: 0,
      name: getBrandOptionsKeyword.value,
      page: 0,
    })
    brandOptions.value = res.data.data.rows
    if (brandOptions.value.length > 0 && !infoForm.brand) {
      infoForm.brand = res.data.data.rows[0].id
    }
    getBrandOptionsLoading.value = false
  }

  // 搜索类型下拉数据
  const searchTypeSelect = (query: string) => {
    typeVal.value = query
    if (query) {
      typeLoading.value = true
      setTimeout(async () => {
        typeLoading.value = false
      }, 1000)
    }
  }

  // 获取单位下拉选项
  const getUnitOptionsKeyword = ref('')
  const getUnitOptionsLoading = ref(false)
  const getUnitOptions = async () => {
    getUnitOptionsLoading.value = true
    const res = await unitPageSelect({
      limit: 0,
      name: getUnitOptionsKeyword.value,
      page: 0,
    })
    unitOptions.value = res.data.data.rows
    getUnitOptionsLoading.value = false
  }

  // 获取参数下拉数据
  const getparaOptions = async (name) => {
    const data = {
      limit: 0,
      name: name,
      page: 0,
    }
    await paramPageSelect(data).then((res) => {
      paraForm.paraOptions = res.data.data.rows
    })
  }

  /**
   * 自定义字段数组，用于渲染，方便调整样式
   */
  const customFieldRender = ref<CustomFieldRender>({
    txtSelect: [],
    uploadFile: [],
    radioCheckboxRate: [],
    textarea: [],
  })

  const setCustomFieldRender = () => {
    customFieldRender.value.radioCheckboxRate = []
    customFieldRender.value.uploadFile = []
    customFieldRender.value.txtSelect = []
    customFieldRender.value.textarea = []
    paraForm.fieldInfo.forEach((field, fieldIndex) => {
      if ([5, 6, 7].includes(field.type)) {
        customFieldRender.value.uploadFile.push({
          sourceArrIndex: fieldIndex,
          name: field.name,
          type: field.type,
          formItemProp: `fieldInfo[${fieldIndex}][imgarr]`,
          rules: [
            {
              required: field.required,
              message: field.tip || '请选择文件',
              trigger: ['change', 'blur'],
            },
          ],
          tip: field.tip || '请选择文件',
          strs: field.strs,
          uploadQty: field.uploadQty,
          uploadSize: field.uploadSize,
        })
      }
      if (field.type === 1 || ([3, 4].includes(field.type) && field.strs?.length > 3)) {
        customFieldRender.value.txtSelect.push({
          sourceArrIndex: fieldIndex,
          name: field.name,
          type: field.type,
          formItemProp: `fieldInfo[${fieldIndex}][val]`,
          rules: [
            {
              required: field.required,
              message: field.tip || (field.type === 1 ? '请输入' : '请选择'),
              trigger: ['change', 'blur'],
            },
          ],
          tip: field.tip || (field.type === 1 ? '请输入' : '请选择'),
          strs: field.strs,
        })
      }
      if (field.type === 8 || ([3, 4].includes(field.type) && field.strs?.length <= 3)) {
        customFieldRender.value.radioCheckboxRate.push({
          sourceArrIndex: fieldIndex,
          name: field.name,
          type: field.type,
          formItemProp: `fieldInfo[${fieldIndex}][val]`,
          rules: [
            {
              required: field.required,
              message: field.tip || '请选择',
              trigger: ['change', 'blur'],
            },
          ],
          tip: field.tip || '请选择',
          strs: field.strs,
        })
      }
      if (field.type === 2) {
        customFieldRender.value.textarea.push({
          sourceArrIndex: fieldIndex,
          name: field.name,
          type: field.type,
          formItemProp: `fieldInfo[${fieldIndex}][val]`,
          rules: [
            {
              required: field.required,
              message: field.tip || '请输入',
              trigger: ['change', 'blur'],
            },
          ],
          tip: field.tip || '请输入',
          strs: field.strs,
        })
      }
    })
  }

  const getCustomFieldLoading = ref(false)

  // 物料参数改变时
  const getFields = (val) => {
    paraForm.fieldInfo = []
    if (val != '') {
      getCustomFieldLoading.value = true
      getParamFields(val).then((res) => {
        getCustomFieldLoading.value = false
        if (res.data.data.rows.length > 0) {
          paraForm.fieldInfo = res.data.data.rows.map((o) => {
            o.goodsParamFieldId = o.id
            o.id = null
            if (o.type == 5 || o.type == 6 || o.type == 7) {
              o.val = []
              o.imgarr = []
            } else if (o.type == 4) {
              o.val = []
            } else {
              o.val = ''
            }
            if (paraForm.paramValVo.paramId == val) {
              paraForm.fieldValVos.map((item) => {
                if (o.goodsParamFieldId == item.goodsParamFieldId) {
                  o.goodsParamFieldId = item.goodsParamFieldId
                  o.id = item.id
                  if (item.type == 5 || item.type == 6 || item.type == 7) {
                    o.imgarr = [...JSON.parse(item.val)]
                  } else if (item.type == 4) {
                    o.val = [...JSON.parse(item.val)]
                  }
                }
              })
            }
            return o
          })
        }
        setCustomFieldRender()
      })
    } else {
      paraForm.fieldInfo = []
    }
  }

  // 获取保存数据加载
  const getSaveDataLoading = ref(false)

  // 请求的数据
  const getData = async () => {
    getSaveDataLoading.value = true
    // 获取分类名称
    if (infoForm.class) {
      typeOptions.value.forEach((item) => {
        if (item.id == infoForm.class) {
          infoForm.className = item.name
        }
      })
    }
    if (infoForm.typeIds.length > 0) {
      infoForm.typeNames = []
      goodsTypeList.value.forEach((item) => {
        if (infoForm.typeIds.includes(item.id)) {
          infoForm.typeNames.push(item.name)
          if (item.childData.length > 0) {
            item.childData.map((item2) => {
              if (infoForm.typeIds.includes(item2.id)) {
                infoForm.typeNames.push(item2.name)
                if (item2.childData.length > 0) {
                  item2.childData.map((item3) => {
                    if (infoForm.typeIds.includes(item3.id)) {
                      infoForm.typeNames.push(item3.name)
                    }
                  })
                }
              }
            })
          }
        }
      })
    }
    // 获取品牌名称
    if (infoForm.brand) {
      brandOptions.value.forEach((item) => {
        if (item.id == infoForm.brand) {
          infoForm.brandName = item.name
        }
      })
    }
    // 获取单位名称
    if (infoForm.unit) {
      unitOptions.value.forEach((item) => {
        if (item.id == infoForm.unit) {
          infoForm.unitName = item.name
        }
      })
    }
    // 上传物料图片
    if (infoForm.fileList.length != 0) {
      const files = []
      infoForm.fileList.forEach((item) => {
        if (item.raw) {
          files.push(item.raw)
        }
      })
      if (files.length != 0) {
        infoForm.images = []
        loading.value = true
        await proAnnexUpload(files).then((res) => {
          res.data.data.rows.forEach((item) => {
            infoForm.images.push({
              image: item,
            })
          })
        })
        loading.value = false
      }
    }
    // 二维码图片
    if (infoForm.qrImages.length != 0) {
      const files = []
      infoForm.qrImages.forEach((item) => {
        if (item.raw) {
          files.push(item.raw)
        }
      })
      if (files.length != 0) {
        infoForm.qrImage = ''
        loading.value = true
        await proAnnexUpload(files).then((res) => {
          res.data.data.rows.forEach((item) => {
            infoForm.qrImage = item
          })
        })
        loading.value = false
      }
    }
    // 上传物料规格图片
    if (images.value.length != 0) {
      const files = []
      let indexArr = []
      images.value.forEach((item, i) => {
        if (item.raw) {
          files.push(item.raw)
          indexArr.push(i)
        }
        if (imgRoutes.value[i] != item) {
          deleteFile([imgRoutes.value[i]]).then()
        }
      })
      if (files.length != 0) {
        await proAnnexUpload(files).then((res) => {
          res.data.data.rows.forEach((item, i) => {
            tableData.value[indexArr[i]].image = item
          })
        })
      }
    }

    if (infoForm.imageIDs.length != 0) {
      deleteFile(infoForm.imageIDs).then()
    }
    // 获取物料过保价格
    tableData.value.forEach((item) => {
      if (!item.overPrice) {
        item.overPrice = '0'
      }
    })
    // 判断规格是否重复
    let isRepeat
    if (tableData.value.length > 1) {
      const newArr = tableData.value.map((item) => item.name)
      isRepeat = newArr.some((x, index, arr) => arr.findIndex((y) => y == x) != index)
    }
    if (isRepeat) {
      HMessageBox.warning('规格名称重复')
      getSaveDataLoading.value = false
      return
    }
    paraForm.paramValVo.fieldValVos = paraForm.fieldInfo

    // 判断物料图片、附件、视频 上传
    if (paraForm.para) {
      for (const key in paraForm.paramValVo.fieldValVos) {
        let item = paraForm.paramValVo.fieldValVos[key]
        if (item.type == 4) {
          item.val = JSON.stringify(item.val)
        }
        if (item.type == 5 || item.type == 6 || item.type == 7) {
          let img = [] //新上传的
          let isImg = [] //已经上传的
          for (const i in item.imgarr) {
            const it = item.imgarr[i]
            if (it.file) {
              img.push(it.file)
            } else {
              isImg.push(it)
            }
          }
          if (img.length > 0) {
            if (item.type == 7) {
              await orderVideoUpload(img).then((res) => {
                if (res.data.success) {
                  for (let i = 0; i < res.data.data.rows.length; i++) {
                    item.val.push({ id: null, image: res.data.data.rows[i] })
                  }
                } else {
                  HMessageBox.error(res.data.message)
                }
              })
            } else {
              await orderAnnexUpload(img).then((res) => {
                if (res.data.success) {
                  for (let i = 0; i < res.data.data.rows.length; i++) {
                    item.val.push({ id: null, image: res.data.data.rows[i] })
                  }
                } else {
                  HMessageBox.error(res.data.message)
                }
              })
            }
          }
          item.val = [...isImg, ...item.val]
          if (item.type == 5 || item.type == 6 || item.type == 7) {
            item.val = JSON.stringify(item.val)
          }
        }
      }
    }
    // 获取物料参数
    if (paraForm.paramValVo.paramId == paraForm.para) {
      paraForm.paramValVo.id = paraForm.paraId
    }
    paraForm.paramValVo.paramId = paraForm.para

    if (editorRef.value) {
      const files = editorRef.value.getUploadFiles().map((file) => file.file)
      const fileTempUrl = editorRef.value.getUploadFiles().map((file) => file.tempUrl)
      if (files.length > 0) {
        const res = await proAnnexUpload(files)
        res.data.data.rows.forEach((fileUrl: string, fileUrlIndex: number) => {
          editorRef.value.convertTempPathToServerPath(fileTempUrl[fileUrlIndex], fileUrl)
        })
      }
    }

    getSaveDataLoading.value = false
    return {
      brand: infoForm.brandName,
      brandId: infoForm.brand,
      code: infoForm.code,
      content: editorRef.value ? await editorRef.value.getEditorValue() : '',
      customParamVos:
        selfData.value.length == 1 && selfData.value[0].name == '' && selfData.value[0].val == ''
          ? []
          : selfData.value,
      delCustomParamIds: paraForm.itemIDs,
      delImageIds: infoForm.imageIDs,
      delSepcIds: delSepcIds.value,
      delextendPathIds: [],
      enabledRegister: infoForm.war,
      extendPathVos: [],
      id: infoForm.proID == '' ? null : infoForm.proID,
      imageVos: infoForm.images,
      instructionBookIds: filtervalue.value,
      itemNumber: infoForm.item,
      model: infoForm.model,
      name: infoForm.name,
      paramValVo: paraForm.paramValVo,
      specVos: tableData.value.map((item) => {
        item.enabled = true
        return item
      }),
      status: infoForm.status,
      supplier: infoForm.supplier,
      supplierTelephone: infoForm.phone,
      type: infoForm.typeNames[0] || '',
      typeId: infoForm.typeIds[0] || '',
      typeThree: infoForm.typeNames[2] || '',
      typeThreeId: infoForm.typeIds[2] || '',
      typeTwo: infoForm.typeNames[1] || '',
      typeTwoId: infoForm.typeIds[1] || '',
      unit: infoForm.unitName,
      unitId: infoForm.unit,
      videoIds: videoValue.value,
      qrImage: infoForm.qrImage,
      productModuleRelationVos: infoForm.productModuleRelationVos,
      coreMaterials: infoForm.coreMaterials,
    }
  }

  // 保存方法
  const saveSuccess = async (method, data, load) => {
    if (!data) {
      return
    }

    load.value = true
    if (data.paramValVo.fieldValVos) {
      data.paramValVo.fieldValVos = data.paramValVo.fieldValVos.map((item) => {
        let tem = []
        if (item.type === 5 || item.type === 6 || item.type === 7) {
          let v = JSON.parse(item.val)
          tem = v.map((o) => {
            return { id: null, optValue: o.image }
          })
        } else if (item.type === 4) {
          let v = JSON.parse(item.val)
          tem = v.map((o) => {
            return { id: null, optValue: o }
          })
        } else {
          tem = [{ id: null, optValue: item.val }]
        }
        return { ...item, optVos: tem }
      })
    }
    data.specVos = data.specVos.map((spec) => {
      spec.price = Number(spec.price)
      spec.overPrice = spec.price
      return spec
    })
    const res = await method(data)
    ElMessage({
      message: res.data.message,
      type: res.data.success ? 'success' : 'error',
      plain: true,
      duration: 5000,
      showClose: true,
    })
    if (res.data.success) {
      refresh()
      TagsViewStore.delView(router.currentRoute.value.path)
      if (data.id) {
        router.push({ path: '/commodity/commodi/detail/' + data.id })
      } else {
        router.push({ path: '/commodity/commodi' })
      }
    }
    load.value = false
  }
  // 取消保存
  const onCancel = () => {
    TagsViewStore.delView(router.currentRoute.value.path)
    if (infoForm.proID) {
      router.push({ path: '/commodity/commodi/detail/' + infoForm.proID })
    } else {
      router.push({ path: '/commodity/commodi' })
    }
  }
  // 保存物料/物料
  const saveData = async (formEl: FormInstance | undefined) => {
    try {
      await formSpec.value.validate()
      await formEl.validate()
      if (infoForm.type == '成品') {
        saveSuccess(productSave, await getData(), loading)
      } else {
        saveSuccess(spareSave, await getData(), loading)
      }
    } catch (error) {
      HMessageBox.error('请输入完整信息！')
    }
  }

  // 获取物料详细
  const getDetail = async () => {
    if (route.params.id != undefined) {
      loading.value = true
      // 成品 物料详情 1
      if (getGoodType() === 'product') {
        await getInfo(route.params.id).then((res) => {
          infoForm.proID = res.data.data.row.id
          infoForm.model = res.data.data.row.model
          infoForm.class = res.data.data.row.typeId
          infoForm.className = res.data.data.row.type
          infoForm.coreMaterials = res.data.data.row.coreMaterials
          infoForm.typeIds = []
          infoForm.typeNames = []
          if (res.data.data.row.typeId) {
            infoForm.typeIds.push(res.data.data.row.typeId)
            if (res.data.data.row.typeTwoId !== '0') {
              infoForm.typeIds.push(res.data.data.row.typeTwoId)
              if (res.data.data.row.typeThreeId !== '0') {
                infoForm.typeIds.push(res.data.data.row.typeThreeId)
              }
            }
          }
          if (res.data.data.row.type) {
            infoForm.typeNames.push(res.data.data.row.type)
            if (res.data.data.row.typeTwo) {
              infoForm.typeNames.push(res.data.data.row.typeTwo)
              if (res.data.data.row.typeThree) {
                infoForm.typeNames.push(res.data.data.row.typeThree)
              }
            }
          }

          infoForm.brand = res.data.data.row.brandId
          infoForm.brandName = res.data.data.row.brand
          infoForm.unit = res.data.data.row.unitId
          infoForm.unitName = res.data.data.row.unit
          infoForm.name = res.data.data.row.name
          infoForm.item = res.data.data.row.itemNumber
          infoForm.war = res.data.data.row.enabledRegister
          infoForm.code = res.data.data.row.code
          infoForm.status = res.data.data.row.status
          rulesForm.name[0].required = true
          rulesForm.item[0].required = true
          rulesForm.code[0].required = true
          infoForm.images = res.data.data.row.imageVos
          infoForm.productModuleRelationVos = res.data.data.row.productModuleRelationVos
          serviceFormSelectIdList.value = res.data.data.row.productModuleRelationVos.map(
            (item) => item.moduleId,
          )

          if (res.data.data.row.imageVos.length != 0) {
            res.data.data.row.imageVos.forEach((item) => {
              infoForm.fileList.push({
                id: item.id,
                url: item.image,
              })
            })
          }
          infoForm.qrImage = res.data.data.row.qrImage
          tableData.value = res.data.data.row.specVos
          res.data.data.row.specVos.forEach((item) => {
            images.value.push(item.image)
            imgRoutes.value.push(item.image)
          })
          nameIndex.value = 0
          paraForm.paraId = res.data.data.row.paramValVo?.id //修改必填
          paraForm.para = res.data.data.row.paramValVo?.paramId
          paraForm.paramValVo.paramId = res.data.data.row.paramValVo?.paramId
          paraForm.fieldValVos = res.data.data.row.paramValVo?.fieldValVos || []
          if (res.data.data.row.paramValVo) {
            getParamFields(paraForm.para).then((res2) => {
              paraForm.fieldInfo = res2.data.data.rows.map((item) => {
                item['goodsParamFieldId'] = item.id
                item.id = null
                return item
              })
              paraForm.fieldInfo = paraForm.fieldInfo.map((o) => {
                if (o.type == 5 || o.type == 6 || o.type == 7) {
                  o.val = []
                  o.imgarr = []
                } else if (o.type == 4) {
                  o.val = []
                } else {
                  o.val = ''
                }
                paraForm.fieldValVos.map((item) => {
                  if (o.goodsParamFieldId == item.goodsParamFieldId) {
                    // o.goodsParamFieldId = item.goodsParamFieldId
                    o.id = item.id
                    if (item.type == 5 || item.type == 6 || item.type == 7) {
                      let ov = item.optVos.map((vo) => {
                        return { id: vo.id, image: vo.optValue }
                      })
                      o.imgarr = [...ov]
                    } else if (item.type == 4) {
                      let ov = item.optVos.map((vo) => vo.optValue)
                      o.val = [...ov]
                    } else {
                      o.val = item.optVos.map((vo) => vo.optValue)[0]
                    }
                  }
                })
                return o
              })
              setCustomFieldRender()
            })
          }
          if (res.data.data.row.customParamVos.length == 0) {
            selfData.value = [
              {
                name: '',
                val: '',
              },
            ]
          } else {
            selfData.value = res.data.data.row.customParamVos
          }
          ediorData.value = { content: res.data.data.row.content, type: 'goods' }
        })
        await getInsDetail(route.params.id).then((res) => {
          filtervalue.value = res.data.data.row
        })
        // await getVideoDetail(route.params.id).then((res) => {
        //   videoValue.value = res.data.data.row
        // })
      } else {
        await getSpareInfo(route.params.id).then((res) => {
          infoForm.proID = res.data.data.row.id
          infoForm.model = res.data.data.row.model
          infoForm.class = res.data.data.row.typeId
          infoForm.className = res.data.data.row.type
          infoForm.typeIds = []
          infoForm.typeNames = []
          if (res.data.data.row.typeId) {
            infoForm.typeIds.push(res.data.data.row.typeId)
            if (res.data.data.row.typeTwoId) {
              infoForm.typeIds.push(res.data.data.row.typeTwoId)
              if (res.data.data.row.typeThreeId) {
                infoForm.typeIds.push(res.data.data.row.typeThreeId)
              }
            }
          }
          if (res.data.data.row.type) {
            infoForm.typeNames.push(res.data.data.row.type)
            if (res.data.data.row.typeTwo) {
              infoForm.typeNames.push(res.data.data.row.typeTwo)
              if (res.data.data.row.typeThree) {
                infoForm.typeNames.push(res.data.data.row.typeThree)
              }
            }
          }
          infoForm.brand = res.data.data.row.brandId
          infoForm.brandName = res.data.data.row.brand
          infoForm.unit = res.data.data.row.unitId
          infoForm.unitName = res.data.data.row.unit
          infoForm.name = res.data.data.row.name
          infoForm.item = res.data.data.row.itemNumber
          infoForm.code = res.data.data.row.code
          infoForm.status = res.data.data.row.status
          infoForm.coreMaterials = res.data.data.row.coreMaterials
          ediorData.value = { content: res.data.data.row.content, type: 'goods' }
          rulesForm.name[0].required = true
          rulesForm.item[0].required = true
          rulesForm.code[0].required = true
          infoForm.images = res.data.data.row.imageVos
          if (res.data.data.row.imageVos.length != 0) {
            res.data.data.row.imageVos.map((item) => {
              infoForm.fileList.push({
                id: item.id,
                url: item.image,
              })
            })
          }
          infoForm.qrImage = res.data.data.row.qrImage
          tableData.value = res.data.data.row.specVos
          nameIndex.value = 0
          paraForm.paraId = res.data.data.row.paramValVo?.id //修改必填
          paraForm.para = res.data.data.row.paramValVo?.paramId
          paraForm.paramValVo.paramId = res.data.data.row.paramValVo?.paramId
          paraForm.fieldValVos = res.data.data.row.paramValVo?.fieldValVos
          if (res.data.data.row.paramValVo) {
            getParamFields(paraForm.para).then((res2) => {
              paraForm.fieldInfo = res2.data.data.rows.map((item) => {
                item['goodsParamFieldId'] = item.id
                item.id = null
                return item
              })
              paraForm.fieldInfo = paraForm.fieldInfo.map((o) => {
                if (o.type == 5 || o.type == 6 || o.type == 7) {
                  o.val = []
                  o.imgarr = []
                } else if (o.type == 4) {
                  o.val = []
                } else {
                  o.val = ''
                }
                paraForm.fieldValVos.map((item) => {
                  if (o.goodsParamFieldId == item.goodsParamFieldId) {
                    // o.goodsParamFieldId = item.goodsParamFieldId
                    o.id = item.id
                    if (item.type == 5 || item.type == 6 || item.type == 7) {
                      let ov = item.optVos.map((vo) => {
                        return { id: vo.id, image: vo.optValue }
                      })
                      o.imgarr = [...ov]
                    } else if (item.type == 4) {
                      let ov = item.optVos.map((vo) => vo.optValue)
                      o.val = [...ov]
                    } else {
                      o.val = item.optVos.map((vo) => vo.optValue)[0]
                    }
                  }
                })
                return o
              })
            })
          }
          if (res.data.data.row.customParamVos.length == 0) {
            selfData.value = [
              {
                name: '',
                val: '',
              },
            ]
          } else {
            selfData.value = res.data.data.row.customParamVos
          }
        })
      }
      loading.value = false
    }
  }

  watch(
    () => route.name,
    (value) => {
      if (value === 'commodity1') {
        pageTitle.value = '新增物料'
      }

      if (value === 'editCommodity') {
        pageTitle.value = '修改成品'
      }
      if (value === 'editCommodity2') {
        pageTitle.value = '修改物料'
      }
    },
    { immediate: true },
  )

  //监听查看附件弹窗关闭时销毁 iframe内存
  watch(dialogContract, (n) => {
    if (!n) {
      file.value.file = ''
    }
  })

  // 在页面被关闭后销毁编辑器
  watch(
    () => TagsViewStore.getReloadPages,
    (value) => {
      if (value.includes(route.path)) {
        if (editorRef.value) {
          editorRef.value.destoryEditor()
        }
      }
    },
    { deep: true, immediate: true },
  )

  onMounted(async () => {
    getGoodsTypeFun().then(() => {
      selectGoodType()
    })
    getBrandOptions()
    getUnitOptions()
    getparaOptions('')
    getOrderModuleOptionList()
    getReturnFactoryModuleOptionList()
    getDetail()

    if (getGoodType() === 'spare') {
      listItem.value = ['基本信息', '物料规格', '物料参数', '物料详情']
    }
    if (paraForm.para || selfData.value[0].name) {
      activeNames.value.push('3')
    }
    nextTick(() => {
      if (editorRef.value) {
        editorRef.value.mountEditor()
      }
    })
  })
</script>

<style lang="scss" scoped>
  .primary-picture {
    width: 80px;
    height: 50px;
    box-shadow: 0 0 0 1px #dcdfe6 inset;

    :deep(.el-upload) {
      width: 100%;
      height: 100%;
    }
  }

  .select_header {
    display: flex;
    column-gap: 5px;
  }

  .add_good_container {
    height: calc(100vh - 92px);
    box-sizing: border-box;
    padding: 12px;
    display: flex;
    flex-direction: column;
    row-gap: 12px;

    .header {
      background-color: #fff;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px;

      .title {
        font-size: 14px;
        // line-height: 16px;
      }

      .btn_group {
        display: flex;
        column-gap: 5px;
      }
    }

    .body {
      height: calc(100% - 64px);
      overflow: auto;
      display: flex;
      flex-direction: column;
      row-gap: 12px;

      #sy4 {
        flex: 1;

        :deep(.el-collapse-item) {
          height: 100%;

          .el-collapse-item__wrap {
            height: calc(100% - 40px);

            .el-collapse-item__content {
              height: 100%;
            }
          }
        }
      }

      &::-webkit-scrollbar {
        display: none;
      }

      .basic_info_form {
        box-sizing: border-box;
        padding: 8.5px 40px 18px 40px;

        :deep(.el-form) {
          display: flex;
          flex-direction: column;
          row-gap: 12px;

          .main {
            // display: flex;
            // flex-wrap: wrap;
            // // flex-direction: column;
            row-gap: 18px;
            column-gap: 48px;
            display: grid;
            grid-template-columns: repeat(3, 360px);

            .item_form {
              display: flex;
              flex-direction: column;
              row-gap: 12px;
              row-gap: 18px;

              .code {
                display: flex;
                column-gap: 3px;

                .icon {
                  height: 28px;
                  display: flex;
                  align-items: center;
                }
              }
            }

            .el-form-item {
              .el-form-item__label {
                height: 28px;
                line-height: 28px;
              }

              .el-form-item__content {
                align-items: flex-start;
                flex-direction: column;

                .el-select,
                .el-input {
                  width: 258px;
                }

                .el-form-item__error {
                  margin: 3px 0 0 0;
                  padding: 0;
                }

                .tip {
                  height: 16px;
                  line-height: 16px;
                  color: $primaryColor;
                }

                .img_list {
                  display: flex;
                  gap: 5px;
                  width: 100%;
                  flex-wrap: wrap;

                  .el-upload {
                    width: 80px;
                    height: 50px;
                    box-shadow: 0 0 0 1px #dcdfe6 inset;
                    background: none;
                    border: none;

                    .iconfont {
                      color: #fff;
                      font-size: 28px;
                      width: 28px;
                      height: 28px;
                      line-height: 28px;
                    }
                  }
                }
              }
            }
          }
        }
      }

      .specification {
        padding: 4px 24px 24px 24px;

        .warr_day {
          display: flex;
          align-items: center;
          column-gap: 5px;
        }

        .iconfont {
          color: #fff;
        }
      }

      .good_parameter {
        padding: 8.5px 56px 18px 56px;
        display: flex;
        column-gap: 100px;

        .table {
          width: calc(100% - 72px - 500px);
        }

        .form {
          width: 500px;

          :deep(.el-form) {
            display: flex;
            flex-direction: column;
            row-gap: 12px;

            .el-form-item {
              .el-form-item__label {
                height: 28px;
                line-height: 28px;
                align-items: center;
              }

              .el-form-item__content {
                flex-direction: column;
                align-items: flex-start;

                .el-checkbox-group {
                  display: flex;
                  flex-wrap: wrap;
                  column-gap: 32px;

                  .el-checkbox {
                    margin: 0;
                    column-gap: 5px;

                    .el-checkbox__label {
                      padding: 0;
                    }
                  }
                }

                .el-radio-group {
                  column-gap: 32px;

                  .el-radio {
                    margin: 0;
                    column-gap: 5px;

                    .el-radio__label {
                      padding: 0;
                      height: 28px;
                      line-height: 28px;
                    }
                  }
                }

                .el-upload {
                  width: 440px;

                  .el-upload-dragger {
                    padding: 0;
                    height: 100px;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    align-items: center;
                  }
                }

                .files {
                  display: flex;
                  gap: 10px;
                  flex-wrap: wrap;
                  margin-top: 10px;

                  .file {
                    list-style: none;
                  }
                }

                .el-textarea {
                  width: 100%;

                  .el-textarea__inner {
                    min-height: 28px !important;
                    height: 28px;
                    max-height: 130px !important;
                    width: 100% !important;
                  }
                }

                .el-form-item__error {
                  margin: 3px 0 0 0;
                  padding: 0;
                }
              }
            }
          }
        }
      }

      .editor_container {
        height: 100%;
        box-sizing: border-box;
        padding: 4px 24px 24px 24px;
      }
    }
  }

  .appcontainer {
    background-color: #f0f2f5;
    padding: 10px;
    position: fixed;
    z-index: 8;
  }

  .content_main {
    margin-bottom: 55px;
  }

  :deep(.w-e-bar-divider) {
    width: 0;
  }

  :deep(.el-form-item--default) {
    --font-size: 12px;
  }

  .header_tabs {
    background-color: #fff;

    .item_title {
      text-align: center;
      padding: 10px;
      font-size: 14px;
      cursor: pointer;
    }

    .is_bg {
      background-color: #007cff;
      color: #fff;
    }
  }

  :deep(.el-collapse-item__header) {
    height: 40px;
    padding: 0 10px;
  }

  :deep(.el-collapse-item__arrow) {
    display: none;
  }

  :deep(.el-collapse-item__content) {
    padding-bottom: 0;
  }

  .bor_padding {
    margin: 12px;

    .bor {
      border: 1px solid #eee;
      margin: 0 10px 10px 10px !important;
    }

    .main_content {
      padding: 10px;
      border-top: 1px solid #eee;

      .text_span {
        color: #999;
        margin-left: 5px;
        font-size: 12px;
      }

      .btn_list {
        margin-right: 5px;
        height: 30px;
        line-height: 30px;
        border-radius: 2px;
        border: 1px solid #007cff;
        color: #007cff;
        background-color: #eaeff8;
        padding: 10px 5px 10px 10px;
        font-weight: bold;

        .icon_btn {
          margin-right: 5px;
          display: inline-block;
        }

        .icon_arr_right {
          margin-left: 20px;
          display: inline-block;
        }
      }

      :deep(.w-e-bar-divider) {
        width: 0;
      }

      :deep {
        .el-checkbox {
          margin-right: 10px;
          align-items: center;

          .el-checkbox__label {
            padding-left: 4px;
          }
        }
      }

      :deep(.el-table .cell) {
        // text-align: center;
        margin: auto;
        overflow: visible;
        width: 100% !important;

        td.el-table__cell {
          text-align: center;
        }
      }

      :deep(.el-main) {
        padding: 0;

        .title_h4 {
          margin-bottom: 10px;
          margin-top: 5px;
        }
      }

      .demo-ruleForm {
        .el-form-item {
          width: 320px;
          margin-bottom: 15px;
          position: relative;

          .tip {
            position: absolute;
            font-size: 12px;
            color: #999;
            line-height: 16px;
            bottom: -30px;
          }

          .plus_add {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            color: #000;
            margin-top: 10px;
          }
        }

        :deep(.el-select .el-input .el-input__wrapper) {
          width: 208px;
        }

        .phone_add {
          margin-top: 10px;

          :deep(.el-upload-list--picture-card) {
            display: flex;
            flex-wrap: nowrap;

            .el-upload-list__item {
              width: 80px;
              height: 80px;
              margin: 8px 0 0 8px;
            }

            .el-upload {
              margin: 8px 0 0 8px;
            }
          }

          .img_view {
            width: 100%;
          }
        }

        .justify {
          display: flex;
          justify-content: start;
          align-items: baseline;
          flex-wrap: wrap;
        }
      }

      .add_title {
        color: #007cff;
        cursor: pointer;
      }

      .delete_label {
        color: red;
        text-align: start;
        padding-left: 10px;
        cursor: pointer;
      }

      .label_color {
        color: #999;
        font-size: 12px;
      }

      .table_list {
        padding-top: 10px;

        .batch_num {
          background-color: #fff;
          box-shadow: 0 0 5px 1px #e5e5e5;
          font-size: 12px;
          padding: 0 6px;
          line-height: 20px;
          height: 20px;
          display: inline-block;
          cursor: pointer;
        }

        .index {
          display: block;
        }

        .dele-icon {
          display: none;
        }

        :deep(.hover-row) {
          .dele-icon {
            display: block;
            cursor: pointer;
          }

          .index {
            display: none;
          }
        }

        :deep(.el-input__inner) {
          font-size: 12px;
        }

        .img-uploader {
          display: flex;
          justify-content: center;
          align-items: center;

          .avatar-uploader-icon {
            padding: 8px;
            border: 1px dashed #e5e5e5;
            background-color: #fff;
          }
        }

        :deep(.el-checkbox) {
          margin-right: 0 !important;

          .el-checkbox__inner {
            width: 20px;
            height: 20px;

            &::after {
              transform: rotate(45deg) scaleY(1.2);
              height: 10px;
              left: 7px;
            }
          }
        }

        .warr_day {
          display: flex;
          align-items: center;
          justify-content: center;

          .day {
            padding-left: 5px;
          }
        }
      }
    }
  }

  .back_w_footer {
    background-color: #fff;
    padding: 10px;
    margin: 0 11px;
    text-align: center;
    position: fixed;
    bottom: 0;
    right: 0;
    z-index: 99;
    box-shadow: 0 0 2px 10px rgb(240, 242, 245);
  }

  .spec_show {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    margin: 30px 10px;

    .label_color {
      color: #999;
      font-size: 14px;
    }
  }

  .dialog-footer {
    .btn_dialog {
      color: #fff;
      width: 80px;
    }

    .btn_dialog_Cancel {
      width: 80px;

      &:hover {
        border: 1px solid #e5e5e5;
        color: #999;
        background-color: #e5e5e5;
      }
    }
  }

  :deep(.el-drawer__header) {
    margin: 0;
  }

  .pro_information {
    p {
      font-style: 12px;
      color: #999;
      margin-bottom: 20px;
    }

    .list_item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 210px;
    }

    :deep(.el-transfer) {
      display: flex;
      justify-content: center;
      align-items: center;
      --el-transfer-panel-width: 300px;

      .el-transfer__buttons {
        width: 70px;
        padding: 0 10px;
        flex-direction: column;
        display: flex;
        justify-content: center;
        align-items: center;

        .el-button {
          padding: 0;
          margin: 0;
          width: 30px;
          height: 26px;

          & + .el-button {
            margin-top: 5px;
          }
        }
      }

      .el-transfer-panel__filter {
        padding: 10px 20px;
        width: 100%;
        margin: 0;
      }
    }

    :deep(.el-transfer-panel .el-checkbox .el-checkbox__label) {
      font-size: 12px;
    }

    .btn_drawer {
      text-align: end;
      margin: 20px;
    }
  }

  .upload_file {
    width: 100%;

    :deep(.el-upload-dragger) {
      padding: 0;
      font-size: 12px;
      height: 40px;
      line-height: 10px !important;
      color: #999;
    }

    .up_icon {
      color: #ccc;
      font-size: 24px;
    }

    .ul_list {
      display: flex;
      max-height: 230px;
      overflow-y: auto;
      justify-content: space-between;
      flex-wrap: wrap;
      padding: 0 6px;

      .li_item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border: 1px solid #e4e7ed;
        padding: 4px 10px;
        width: calc(90% - 0px);
        color: #999;
        font-size: 12px;
        margin-top: 10px;
        padding-right: 10px;
        border-radius: 2px;

        .li_item_left {
          display: flex;
          align-items: center;
          width: calc(100% - 15px);

          .pic_name {
            padding-left: 10px;
            color: #000;
            margin-right: 5px;
            text-overflow: ellipsis;
            white-space: nowrap;
            width: 70%;
            overflow: hidden;
          }
        }
      }
    }
  }

  .pop_aside {
    background-color: #fff;
    box-sizing: border-box;

    .oard_form {
      max-height: 280px;
      overflow-y: auto;
    }

    .oard_form_ {
      display: flex;
      flex-wrap: wrap;
      margin-right: 20px;

      :deep(.el-radio__label) {
        font-size: 12px;
      }

      :deep(.el-textarea__inner) {
        font-size: 12px;
      }

      :deep(.el-checkbox__label) {
        font-size: 12px;
      }

      .el-form-item {
        width: 290px !important;
        margin-right: 20px;
      }

      .ul_list {
        display: block !important;

        .li_item {
          width: auto !important;
        }
      }
    }
  }

  .can_shu {
    display: flex;
    justify-content: center;
    align-items: center;

    .icon {
      margin-left: 8px;
      cursor: pointer;
    }

    .icons {
      width: 80px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
</style>
